package com.learner.trade.controller.api;

import com.learner.common.util.JwtInfo;
import com.learner.common.util.JwtUtils;
import com.learner.pojo.trade.Order;
import com.learner.trade.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;


/**
 * @Description:
 * @Author: ice2020x
 * @Date: 2021/10/27
 */
@RequestMapping("/api/trade/order")
@CrossOrigin
@RestController
@Slf4j
public class ApiOrderController {

    @Autowired
    private OrderService orderService;


    /**
     * 生成订单
     *
     * @param courseId 课程id
     * @param request  request
     * @return 结果
     */
    @PostMapping("/auth/save/{courseId}")
    public Order save(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        JwtInfo memberIdByJwtToken = JwtUtils.getInfoByJwtToken(request);
        return orderService.saveOrder(courseId, memberIdByJwtToken.getUserId());
    }

    /**
     * 根据订单id和用户id获取订单
     *
     * @param orderId 订单id
     * @param request request
     * @return order
     */
    @GetMapping("/auth/get/{orderId}")
    public Order get(@PathVariable("orderId") String orderId, HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        return orderService.getById(orderId, userId);
    }

    /**
     * 判断该用户是否购买该课程
     *
     * @param courseId 课程id
     * @param request  request
     * @return 结果
     */
    @GetMapping("/auth/is_buy/{courseId}")
    public boolean isBuyByCourseId(@PathVariable("courseId") String courseId, HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        return orderService.isBuyByCourseId(courseId, userId);
    }


    /**
     * 获取当前用户的一个订单列表
     *
     * @param request request
     * @return 结果
     */
    @GetMapping("/auth/list")
    public List<Order> list(HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        return orderService.selectByMemberId(userId);
    }

    /**
     * 根据id删除当前用户的一个订单
     *
     * @param orderId 课程id
     * @param request request
     */
    @DeleteMapping("/auth/remove/{orderId}")
    public void remove(@PathVariable("orderId") String orderId, HttpServletRequest request) {
        String userId = JwtUtils.getCurrentUserId(request);
        orderService.remove(orderId, userId);
    }


}
